<template>
  <basic-container>
    <avue-crud
      :option="option"
      :search.sync="search"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @sort-change="sortChange"
      @on-load="onLoad"
    >
      <template slot-scope="scope" slot="remarkForm">
        <audit-record :rejectRecord="scope.value" ref="toAuditRecord" />
      </template>
      <template slot-scope="{ row, index }" slot="menu">
        <el-button
          type="text"
          icon="el-icon-edit"
          size="small"
          v-if="row.rpiExStatus == '3' || row.rpiExStatus == '4'"
          @click="$refs.crud.rowEdit(row, index)"
          >编 辑</el-button
        >
      </template>
      <!-- <template slot="menuLeft">
        <el-button
          type="danger"
          size="small"
          icon="el-icon-delete"
          plain
          v-if="permission.pos_info_delete"
          @click="handleDelete"
          >删 除
        </el-button>
      </template>
      <template slot="menuRight">
        <el-button
          type="success"
          size="small"
          plain
          icon="el-icon-upload2"
          v-if="permission.pos_info_import"
          @click="handleImport"
          >导入
        </el-button>
        <el-button
          type="warning"
          size="small"
          plain
          icon="el-icon-download"
          v-if="permission.pos_info_export"
          @click="handleExport"
          >导出
        </el-button>
      </template> -->
      <template slot-scope="{ row }" slot="rpiExStatus">
        <el-tag type="success" :color="getColorRpiExStatus(row.rpiExStatus)" effect="dark">{{ row.rpiExStatusName }}</el-tag>
      </template>
    </avue-crud>
    <el-dialog
      title="数据导入"
      append-to-body
      :visible.sync="excelBox"
      width="555px"
    >
      <avue-form
        :option="excelOption"
        v-model="excelForm"
        :upload-after="uploadAfter"
      >
        <template slot="excelTemplate">
          <el-button type="primary" @click="handleTemplate">
            点击下载<i class="el-icon-download el-icon--right"></i>
          </el-button>
        </template>
      </avue-form>
    </el-dialog>
  </basic-container>
</template>

<script>
import {
  getList,
  getDetail,
  addGroup,
  updateGroup,
  updateGroupPlus,
  remove,
} from "@/api/rb-merchant/posinfo/pos_info";
import { getRegion } from "@/api/system/dict";
import { mapGetters } from "vuex";
import { getToken } from "@/util/auth";
import { isMobile } from "@/util/validate";
import auditRecord from "@/components/rb-merchant/audit-record.vue";

export default {
  components: {
    auditRecord
  },
  data() {
    const validatePhone = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!isMobile(value)) {
        callback(new Error("手机号码不正确！"));
      } else {
        callback();
      }
    };
    return {
      form: {},
      query: {},
      search: {},
      userType: "3",
      props: {
        //菜单权限数据 props
        label: "title",
        value: "key",
      },
      loading: true,
      excelBox: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        rpiKind: 1,
        total: 0,
      },
      selectionList: [],
      option: {
        // height: "auto",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: true,
        editBtn: false,
        delBtn: false,
        selection: true,
        searchMenuSpan: 6,
        columnBtn: false,
        column: [
          {
            label: "主键",
            prop: "id",
            type: "input",
            //sortable: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            hide: true,
          },
          {
            label: "用户编号",
            prop: "userNo",
            type: "input",
            //sortable: true,
            display: false,
            hide: true,
            overHidden: true,
          },
          {
            label: "商户类型",
            prop: "rpiTypeName",
            //sortable: true,
            slot: true,
            display: false,
            overHidden: true,
            width: 100
          },
          {
            label: "商户类型",
            prop: "rpiType",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=rpi_type",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            showColumn: false,
            hide: true,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入商户类型",
                trigger: "blur",
              },
            ],
            overHidden: true,
            width: 100
          },
          {
            label: "行业类目名称",
            prop: "rpiMccName",
            type: "input",
            display: false,
            rules: [
              {
                required: true,
                message: "请输入行业类目名称",
                trigger: "blur",
              },
            ],
            overHidden: true,
            width: 100
          },
          {
            label: "行业类目",
            prop: "rpiMccCode",
            type: "select",
            dicUrl: "/api/rb-merchant/merchant/mcc/mcc/selectMcc",
            props: {
              label: "industryName",
              value: "industryCode",
            },
            search: true,
            span: 12,
            filterable: true,
            showColumn: false,
            hide: true,
            rules: [
              {
                required: true,
                message: "请选择行业类目",
                trigger: "blur",
              },
            ],
            overHidden: true,
            width: 100
          },
          {
            label: "客户经理",
            prop: "accountManager",
            type: "select",
            dicUrl: "/api/rb-merchant/merchant/posinfo/pos_info/accountManagerList?createUser={{key}}",
            props: {
              label: "userName",
              value: "userId",
            },
            dataType: "string",
            showColumn: false,
            filterable: true,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入审核状态",
                trigger: "blur",
              },
            ],
            overHidden: true,
            width: 100
          },
          {
            label: "商户简称",
            prop: "rpiName",
            type: "input",
            search: true,
            rules: [
              {
                required: true,
                message: "请输入商户简称",
                trigger: "blur",
              },
            ],
            overHidden: true,
            width: 100
          },
          {
            label: "商户号",
            prop: "rpiNo",
            type: "input",
            display: false,
            //sortable: true,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入商户号",
                trigger: "blur",
              },
            ],
            overHidden: true,
            width: 150
          },
          {
            label: "联系人",
            prop: "contactName",
            search: true,
            rules: [
              {
                required: true,
                message: "请输入联系人",
                trigger: "blur",
              },
            ],
            overHidden: true,
            width: 100
          },
          {
            label: "联系电话",
            prop: "contactNumber",
            search: true,
            rules: [
              {
                required: true,
                validator: validatePhone,
                trigger: "blur",
              },
            ],
            overHidden: true,
            width: 150
          },
          // {
          //   label: "归属集团",
          //   prop: "rpiGroup",
          //   type: "input",
          //   span: 24,
          //   //sortable: true,
          //   rules: [
          //     {
          //       required: true,
          //       message: "请输入归属集团",
          //       trigger: "blur",
          //     },
          //   ],
          // },
          {
            label: "省份",
            prop: "provinceName",
            slot: true,
            display: false,
          },
          {
            label: "地市",
            prop: "cityName",
            slot: true,
            display: false,
          },
          {
            label: "区县",
            prop: "areaName",
            slot: true,
            display: false,
          },
          {
            label: "省份",
            prop: "province",
            slot: true,
            display: false,
            hide: true,
          },
          {
            label: "地市",
            prop: "city",
            slot: true,
            display: false,
            hide: true,
          },
          {
            label: "区县",
            prop: "area",
            slot: true,
            display: false,
            hide: true,
          },
          {
            label: "省份/地市/区县",
            labelWidth: 130,
            prop: "provinceCityArea",
            type: "cascader",
            props: {
              label: "name",
              value: "code",
            },
            lazy: true,
            lazyLoad(node, resolve) {
              let stop_level = 2;
              let level = node.level;
              let data = node.data || {};
              let code = data.code;
              let list = [];
              let callback = () => {
                resolve(
                  (list || []).map((ele) => {
                    return Object.assign(ele, {
                      leaf: level >= stop_level,
                    });
                  })
                );
              };
              if (level == 0) {
                getRegion(code).then(
                  (res) => {
                    list = res.data.data;
                    callback();
                  },
                  (error) => {
                    window.console.log(error);
                  }
                );
              } else if (level == 1) {
                getRegion(code).then(
                  (res) => {
                    list = res.data.data;
                    callback();
                  },
                  (error) => {
                    window.console.log(error);
                  }
                );
              } else if (level == 2) {
                getRegion(code).then(
                  (res) => {
                    list = res.data.data;
                    callback();
                  },
                  (error) => {
                    window.console.log(error);
                  }
                );
              } else {
                callback();
              }
            },
            span: 24,
            showColumn: false,
            hide: true,
            rules: [
              {
                required: true,
                message: "请选择省份/地市/区县",
                trigger: "blur",
              },
            ],
            overHidden: true,
            width: 200
          },
          {
            label: "详细地址",
            prop: "address",
            span: 24,
            minRows: 2,
            type: "textarea",
            hide: true,
            rules: [
              {
                required: true,
                message: "请输入详细地址",
                trigger: "blur",
              },
            ],
            overHidden: true,
            width: 200
          },
          {
            label: "审核状态",
            prop: "rpiExStatus",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=rpi_ex_status",
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dataType: "string",
            display: false,
            showColumn: false,
            search: true,
            rules: [
              {
                required: true,
                message: "请输入审核状态",
                trigger: "blur",
              },
            ],
            overHidden: true,
          },
          {
            label: "审核备注",
            prop: "adminRemark",
            overHidden:true,
            width: 150,
            span: 24,
            addDisplay: false,
            editDisplay: false,
          },
          // {
          //   label: "审核时间",
          //   prop: "auditTime",
          //   width: 150,
          //   slot: true,
          //   span: 24,
          //   addDisplay: false,
          //   editDisplay: false,
          // },
          {
            label: "创建时间",
            prop: "createTime",
            width: 150,
            slot: true,
            span: 24,
            addDisplay: false,
            editDisplay: false,
            overHidden: true,
          },
        ],
      },
      data: [],
      excelForm: {},
      excelOption: {
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: "模板上传",
            prop: "excelFile",
            type: "upload",
            drag: true,
            loadText: "模板上传中，请稍等",
            span: 24,
            propsHttp: {
              res: "data",
            },
            tip: "请上传 .xls,.xlsx 标准格式文件",
            action: "/api/rb-merchant/merchant/posinfo/pos_info/import",
          },
          {
            label: "模板下载",
            prop: "excelTemplate",
            formslot: true,
            span: 24,
          },
        ],
      },
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.pos_info_add, false),
        viewBtn: this.vaildData(this.permission.pos_info_view, false),
        delBtn: this.vaildData(this.permission.pos_info_delete, false),
        editBtn: this.vaildData(this.permission.pos_info_edit, false),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    getColorRpiExStatus() {
      return state => {
        if (state == '0') {
          return '#E6A23C';
        } else if (state == '1') {
          return '#396afc';
        } else if (state == '2') {
          return '#E6A23C';
        } else if (state == '3') {
          return '#67C23A';
        } else if (state == '4') {
          return '#F56C6C';
        } else {
          return '#8e9eab';
        }
      }
    }
  },
  created() {
  },
  methods: {
    rowSave(row, done, loading) {
      [row.province, row.city, row.area] = row.provinceCityArea;
      addGroup(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      [row.province, row.city, row.area] = row.provinceCityArea;
      if (row.rpiExStatus == "3") {
        updateGroup(row).then(
          () => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            done();
          },
          (error) => {
            loading();
            window.console.log(error);
          }
        );
      } else if (row.rpiExStatus == "4") {
        updateGroupPlus(row).then(
          () => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            done();
          },
          (error) => {
            loading();
            window.console.log(error);
          }
        );
      }
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        if (this.form.rpiExStatus == "4") {
          const column = this.findObject(this.option.column, "remark");
          column.editDisplay = true;
        }
        getDetail(this.form.rpiNo).then((res) => {
          this.form = res.data.data;
          this.form.provinceCityArea = [
            this.form.province,
            this.form.city,
            this.form.area,
          ];
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(
        page.currentPage,
        page.pageSize,
        page.rpiKind,
        Object.assign(params, this.query)
      ).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    handleImport() {
      this.excelBox = true;
    },
    handleExport() {
      let exQuery = ``;
      exQuery += `&rpiName=${this.search.rpiName}`;
      exQuery += `&rpiNo=${this.search.rpiNo}`;
      exQuery += `&province=${this.search.province}`;
      exQuery += `&city=${this.search.city}`;
      exQuery += `&area=${this.search.area}`;
      exQuery += `&rpiExStatus=${this.search.rpiExStatus}`;
      exQuery += `&rpiStatus=${this.search.rpiStatus}`;
      exQuery += `&rpiType=${this.search.rpiType}`;
      exQuery += `&rpiToken=${this.search.rpiToken}`;
      exQuery += `&rpiMccCode=${this.search.rpiMccCode}`;
      exQuery += `&rpiMccName=${this.search.rpiMccName}`;
      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        window.open(
          `/api/rb-merchant/merchant/posinfo/pos_info/export?${
            this.website.tokenHeader
          }=${getToken()}` + exQuery
        );
      });
    },
    handleTemplate() {
      window.open(
        `/api/rb-merchant/merchant/posinfo/pos_info/export-template?${
          this.website.tokenHeader
        }=${getToken()}`
      );
    },
    uploadAfter(res, done) {
      this.excelBox = false;
      this.refreshChange();
      done();
    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop;
        this.query.descs = "";
      } else {
        //倒序
        this.query.descs = val.prop;
        this.query.ascs = "";
      }
      this.refreshChange();
    },
  },
};
</script>

<style lang="scss" scoped>
/deep/ .el-tag--dark.el-tag--success {
  border-color: transparent;
  opacity: 0.8;
}
</style>
